package com.yazdee.productdetail;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.yazdee.R;
import com.yazdee.config.ConfigValues;

public class ProductDetail extends Activity {
	
	private TextView mName;
	private TextView mPrice;
	private TextView mDescription;
	private ImageView mImage;
	private TextView mRating;
	private String type;
	private Button mTweet;
	private ProgressDialog progress;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.productdetailpage);
		
		mName=(TextView)findViewById(R.id.detailname);
		mPrice=(TextView)findViewById(R.id.detailprice);
		mImage=(ImageView)findViewById(R.id.detailimage);
		mTweet=(Button)findViewById(R.id.detailTweetBtn);
		Bundle extras = getIntent().getExtras();
	    type = extras != null ? extras.getString("Type"): null;
	    
		populateFields();
	}
	
	private void populateFields(){
		ProductDetailHandler elementHandler;
		
			try {
				URL url;
				
				if(type.equals("Browse"))
				url = new URL(ConfigValues.ProductDetailCategoryURL);
				else url=new URL(ConfigValues.ProductDetailSearchURL);
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();

				XMLReader xr = sp.getXMLReader();

				elementHandler = new ProductDetailHandler();
				xr.setContentHandler(elementHandler);
				
				xr.parse(new InputSource(url.openStream()));
				final ProductObject product=elementHandler.getProductDetail();
				mName.setText(Html.fromHtml("<b>"+product.getName()+"</b>"));
				mPrice.setText(Html.fromHtml("<b>Price:</b> "+product.getPrice()));
				
				if(product.getImageURL()!=null && !"".equals(product.getImageURL())) {
				Drawable image = ImageOperations(this,product.getImageURL(),"");
				mImage.setImageDrawable(image); 
				
				/*mTweet.setOnClickListener(new View.OnClickListener(){
					public void onClick(View v){
						try {
							progress = ProgressDialog.show(ProductDetail.this,
									"Updating your status",
									"Please wait...", false);

							Thread updateStatus = new Thread() {

								public void run() {
									Message message = new Message();
									
									StringBuffer tweet=new StringBuffer("Hey checkout ");
									if(mName.length()>100)
										tweet.append(mName.getText().toString().substring(0,100)).append(" at ");
									
									
									if(twitterUName!=null) {
									String status = "Reading "
											+ title.substring(100) + " and it's really "
											+ rating;
									
									BookzieTwitterHelper twitter = new BookzieTwitterHelper(
											twitterUName, twitterPasswd);
									try {
										twitter.updateStatus(status);
									} catch(TwitterException e){
										message.arg2=1;
									}
									message.arg1=2;
									} else {
										message.arg1=1;
									}
									
									
					                DefaultHttpClient client = new DefaultHttpClient();
					                HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);                
					                HttpResponse response;
					                HttpEntity entity;        
					                try {
					                    HttpPost post = new HttpPost(ConfigValues.PostUpdateURL);
					                    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
					                    nvps.add(new BasicNameValuePair("title", title));
					                    nvps.add(new BasicNameValuePair("rating", rating));
					                    nvps.add(new BasicNameValuePair("comment", comment));
					                    nvps.add(new BasicNameValuePair("useremailid", prefs.getString("emailid",null)));
					                    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
					                    post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
					                    response = client.execute(post);
					                    entity = response.getEntity();
					                    InputStream is = entity.getContent();
					                    read(is);
					                    is.close();
					                    if (entity != null) entity.consumeContent();
					                } catch (Exception e) {
					                    createDialog("Error", "Couldn't establish a connection");
					                }
								}
							};
							updateStatus.start();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});*/
				}
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (FactoryConfigurationError e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
 }
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		  super.onSaveInstanceState(outState);
	      //outState.putString("ASIN", mASIN);
	}

	  private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
			try {
				InputStream is = (InputStream) this.fetch(url);
				Drawable d = Drawable.createFromStream(is, "src");
				return d;
			} catch (MalformedURLException e) {
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		}

		public Object fetch(String address) throws MalformedURLException,IOException {
			URL url = new URL(address);
			Object content = url.getContent();
			return content;
		}

}